package jp.wug;

import com.google.inject.Inject;
import com.google.inject.servlet.SessionScoped;

import javax.servlet.ServletRequest;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@SessionScoped
public class WugSession {
    Locale locale;
    Map<String, WugConversation> conversations = new HashMap<String, WugConversation>();

    private final String CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyz";
    private SecureRandom random = new SecureRandom();

    @Inject
    public WugSession(ServletRequest request) {
        if (locale == null) {
            locale = request.getLocale();
        }
    }

    public Locale getLocale() {
        return locale;
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    private String generateRandomString(int length) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int n = random.nextInt(CHARACTERS.length());
            buffer.append(CHARACTERS.charAt(n));
        }
        return buffer.toString();
    }

    public boolean hasConversation(String key) {
        return conversations.containsKey(key);
    }

    public WugConversation getConversation(String key) {
        return conversations.get(key);
    }

    public String startConversation() {
        String key = generateRandomString(16);
        while (conversations.containsKey(key)) {
            key = generateRandomString(16);
        }
        conversations.put(key, new WugConversation(key));
        return key;
    }

//    List<Ticket> ticketList;
//
//    static class Ticket {
//        long validTill;
//
//    }
}